package test.thread.tmp;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionExample {

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public static AtomicLong luckyOne = new AtomicLong(0);

    public void requestToken(String redisKey) {
        long num = luckyOne.incrementAndGet();
        if (num != 1) {
            System.out.println("我没抢到");
            try {
                lock.lock();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我释放了锁");
            lock.unlock();
        }
        if (num == 1) {
            try {
                // 锁住只用一个线程获取token
                lock.lock();
                System.out.println("我获得了锁");
                Thread.sleep(2000);
                condition.signalAll();
                lock.unlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
        }
        System.out.println("1111111111");

    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(5);
        final ConditionExample conditionExample = new ConditionExample();
        for (int i = 0; i < 10; i++) {
            exec.execute(new Runnable() {
                @Override
                public void run() {
                    conditionExample.requestToken("111");
                }
            });
        }

        exec.shutdown();

    }
}
